package com.example.javaproject.datastructure.stack;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * Description:
 * <br>Author：tian
 * <br>Time: 2019/3/11 16:48
 */
public class ArrayStack {
    //存储元素的数组,声明为Object类型能存储任意类型的数据
    private Object[] elementData;
    //指向栈顶的指针
    private int top;
    //栈的总容量
    private int size;


    //默认构造一个容量为10的栈
    public ArrayStack() {
        this.elementData = new Object[10];
        this.top = -1;
        this.size = 10;
    }

    public ArrayStack(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("栈初始容量不能小于0: " + initialCapacity);
        }
        this.elementData = new Object[initialCapacity];
        this.top = -1;
        this.size = initialCapacity;
    }


    //压入元素
    public Object push(Object item) {
        //是否需要扩容
        isGrow(top + 1);
        elementData[++top] = item;
        return item;
    }

    //弹出栈顶元素
    public Object pop() {
        Object obj = peek();
        remove(top);
        return obj;
    }

    //获取栈顶元素
    public Object peek() {
        if (top == -1) {
            throw new EmptyStackException();
        }
        return elementData[top];
    }

    //判断栈是否为空
    public boolean isEmpty() {
        return (top == -1);
    }

    //删除栈顶元素
    public void remove(int top) {
        //栈顶元素置为null
        elementData[top] = null;
        this.top--;
    }

    /**
     * 是否需要扩容
     *
     * @param minCapacity
     * @return
     */
    public boolean isGrow(int minCapacity) {
        int oldCapacity = size;
        if (minCapacity < oldCapacity) {
            return false;
        }

        int newCapacity = 0;
        //左移以为，数字夸大2倍；再与最大整数做比较
        if ((oldCapacity << 1) < Integer.MAX_VALUE) {
            newCapacity = oldCapacity << 1;
        } else {
            newCapacity = Integer.MAX_VALUE;
        }

        this.size = newCapacity;
        //构建数组进行copy
        Object[] newArray = new Object[size];
        elementData = Arrays.copyOf(elementData, size);
        return true;
    }

    public static void main(String[] args) {
//        ArrayStack stack = new ArrayStack(3);
//        stack.push(1);
//        //System.out.println(stack.peek());
//        stack.push(2);
//        stack.push(3);
//        stack.push("abc");
//        System.out.println(stack.peek());
//        stack.pop();
//        stack.pop();
//        stack.pop();
//        System.out.println(stack.peek());

        ArrayStack stack = new ArrayStack(10);
        stack.testStringReversal();

    }

    public void testStringReversal(){
        ArrayStack stack = new ArrayStack();
        String str = "how are you";
        char[] cha = str.toCharArray();
        for(char c : cha){
            stack.push(c);
        }
        while(!stack.isEmpty()){
            System.out.print(stack.pop());
        }
    }


}
